<?php

class haendlerbund_importer {
    #Klassenvariablen

    var $api = false;
    var $api_config = false;
    var $data = array();

    #Konstruktor

    function haendlerbund_importer() {
        
    }

    #Process Methode: Verarbeitet die Formulardaten, validiert sie und importiert die Daten in die DB.

    function process($api_config) {
        $agb_service = array("haendlerbund_impressum|Impressum" => "1293C20B491",
            "haendlerbund_agb|AGB" => "12766C46A8A",
            "haendlerbund_widerruf|Widerrufsbelehrung" => "12766C53647",
            "haendlerbund_rueckgabe|R&uuml;ckgaberecht" => "12766C4A6BE",
            "haendlerbund_versandinfo|Zahlung und Versand" => "12766C58F26",
            "haendlerbund_datenschutz|Datenschutzerkl&auml;rung" => "12766C5E204",
            "haendlerbund_batteriegesetz|Hinweise zur Batterieentsorgung" => "134CBB4D101");

        if ($_POST["config_save"] == 1) {
            $this->saveConfiguration($data);
        }

        if ($_POST['agb_import'] == 1 || $api_config == 1) {
            if ($api_config == 1) {
                $apikey = $_GET["api_key"];
            } else {
                $apikey = $this->getConfigurationValue("haendlerbund_key");
            }


            $check_array = array();
            $error = "";
            $_SESSION["import_message"] = "";

            foreach ($agb_service as $agb_array => $key) {
                $agb_array = explode("|", $agb_array);
                $agb = $agb_array[0];
                $agb_name = $agb_array[1];
                $url = "https://www.hb-intern.de/www/hbm/api/live_rechtstexte.htm?APIkey=1IqJF0ap6GdDNF7HKzhFyciibdml8t4v&did=" . $key . "&AccessToken=" . $apikey;

                $curl = curl_init();
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($curl, CURLOPT_HEADER, 0);
                //curl_setopt($curl, CURLOPT_POST, true);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($curl, CURLOPT_USERAGENT, "INPUT DATA SCRIPT");
                curl_setopt($curl, CURLOPT_URL, $url);
                $result = curl_exec($curl);
                curl_close($curl);

                //$result = file_get_contents($url);
                $result = str_replace("€", "&euro;", $result);

                $result = strip_tags($result, "<p><a><br /><br>\n<strong><b>");

                if ($api_config == 1) {
                    if (!preg_match("/DOCUMENT_NOT_AVAILABLE/i", $result) && !preg_match("/SHOP_NOT_FOUND/i", $result)) {
                        $check_array[] = $agb;
                        echo "<br/>";
                        echo "<br/>";
                        echo $this->getContentIDSelect($agb_name, $agb, $agb);
                        mysql_query("UPDATE configuration SET configuration_value='1' WHERE configuration_key='" . $agb . "_hbon'");
                    } else {
                        mysql_query("UPDATE configuration SET configuration_value='0' WHERE configuration_key='" . $agb . "_hbon'");
                    }
                }

                if ($_POST['agb_import'] == 1 && !preg_match("/DOCUMENT_NOT_AVAILABLE/i", $result) && !preg_match("/SHOP_NOT_FOUND/i", $result)) {
                    if ($this->updateContent($this->getConfigurationValue($agb), utf8_decode(str_replace('style="font-size: medium;"', "", str_replace('style="font-size: 14px;"', "", $result)))) == "1") {
                        $_SESSION["import_message"] = "Import erfolgreich abgeschlossen!";
                    }
                }
            }

            if (count($check_array) == 0 && $api_config == 1) {
                echo "<br /><p align='center' style='color:red'>Es konnten keine Rechtstexte gefunden werden. <br />Bitte &uuml;berpr&uuml;fen Sie Ihren API-Key oder wenden Sie sich an den Support.<input type='hidden' name='api_check_ok' id='api_check_ok' value='0' /></p>";
            } else {
                echo "<input type='hidden' name='api_check_ok' id='api_check_ok' value='1' />";
            }

            if (strtolower($_SESSION['language_charset']) != "utf-8")
                $return = utf8_encode($return);
            return $return;
        }
    }

    #checkErrors Methode: Validiert die Formulardaten

    function checkErrors($arRequired) {
        foreach ($arRequired as $key => $element) {
            if (empty($_POST[$element]))
                return true;
        }
        return false;
    }

    #getFormData Methoda: Entschaerft die Formulardaten fuer eine sichere Verwendung der Variablen in einer MySQL-Query

    function getFormData($array) {
        $data = array();
        foreach ($array as $key => $dataname) {
            $data[$dataname] = mysql_real_escape_string($_POST[$dataname]);
        }
        return $data;
    }

    #saveConfiguration Methode: Speichert alle im Parameter uebergebenen Konfigurationen in der DB.

    function saveConfiguration() {
        foreach ($_POST as $configuration_key => $configuration_value) {
            if (preg_match("/haendlerbund/", $configuration_key)) {

                $sql = mysql_query("SELECT * FROM configuration WHERE configuration_key='" . $configuration_key . "' LIMIT 1");
                if (mysql_num_rows($sql))
                    mysql_query("UPDATE configuration SET configuration_value='" . $configuration_value . "' WHERE configuration_key='" . $configuration_key . "' LIMIT 1");
            }
        }
    }

    #getConfigurationValue Methode: Holt einen Konfigurations-Wert aus der DB, passend zum via Parameter uebergebenen Schluessel

    function getConfigurationValue($key) {
        $value = false;
        $sqlConfiguration = mysql_query("SELECT * FROM configuration WHERE configuration_key='" . $key . "' LIMIT 1");
        if (mysql_num_rows($sqlConfiguration) AND !$value) {
            $dataConfiguration = mysql_fetch_object($sqlConfiguration);
            $value = $dataConfiguration->configuration_value;
        }
        return $value;
    }

    #updateContent Methode: Eigentliche Import-Methode fuer die Texte in die DB

    function updateContent($content_id, $content_text) {
//      if(strtolower($_SESSION['language_charset']) != "utf-8") $content_text = utf8_decode($content_text);
        $return = mysql_query("UPDATE content_manager SET content_text='" . $content_text . "' WHERE content_id=" . $content_id . " LIMIT 1");
        if (!mysql_error()) {
            $return = 1;
        }
        return $return;
    }

    function install() {
        xtc_db_query("INSERT INTO configuration ( configuration_key )  VALUES  ( 'haendlerbund_key'  ) ");
        xtc_db_query("INSERT INTO configuration ( configuration_key ) VALUES  ( 'haendlerbund_impressum_hbon') ");
        xtc_db_query("INSERT INTO configuration ( configuration_key ) VALUES  ( 'haendlerbund_agb_hbon') ");
        xtc_db_query("INSERT INTO configuration ( configuration_key ) VALUES  ( 'haendlerbund_widerruf_hbon') ");
        xtc_db_query("INSERT INTO configuration ( configuration_key ) VALUES  ( 'haendlerbund_rueckgabe_hbon') ");
        xtc_db_query("INSERT INTO configuration ( configuration_key ) VALUES  ( 'haendlerbund_versandinfo_hbon') ");
        xtc_db_query("INSERT INTO configuration ( configuration_key ) VALUES  ( 'haendlerbund_datenschutz_hbon') ");
        xtc_db_query("INSERT INTO configuration ( configuration_key ) VALUES  ( 'haendlerbund_batteriegesetz_hbon') ");
        xtc_db_query("INSERT INTO configuration ( configuration_key ) VALUES  ( 'haendlerbund_impressum') ");
        xtc_db_query("INSERT INTO configuration ( configuration_key ) VALUES  ( 'haendlerbund_agb') ");
        xtc_db_query("INSERT INTO configuration ( configuration_key ) VALUES  ( 'haendlerbund_widerruf') ");
        xtc_db_query("INSERT INTO configuration ( configuration_key ) VALUES  ( 'haendlerbund_versandinfo') ");
        xtc_db_query("INSERT INTO configuration ( configuration_key ) VALUES  ( 'haendlerbund_datenschutz') ");
        xtc_db_query("INSERT INTO configuration ( configuration_key ) VALUES  ( 'haendlerbund_batteriegesetz') ");
    }

    #getImportForm Methode: Generiert das Modul-Formular

    function getImportForm() {
        $installCheck = xtc_db_query("SELECT * FROM " . TABLE_CONFIGURATION . " WHERE configuration_key='haendlerbund_key'  LIMIT 1");
        if (xtc_db_num_rows($installCheck) == 0) {
            $this->install();
        }
        $return = "";


        if ($this->getConfigurationValue("haendlerbund_key") == "" || $_GET["start_konfig"] == 1) {

            $return .= '<div class="content" id="container">
    <div class="title_hb">
      <h5 class="title_hb">Schnittstellen-Konfiguration</h5>
  
    </div>
	<br />
        Bitte konfigurieren Sie Ihr pers&ouml;nliches H&auml;ndlerbund Modul indem Sie die folgenden 2 Schritte durchlaufen. 

    <form action="haendlerbund.php" method="post" class="mainForm" id="mainForm">
<input type="hidden" name="config_save" value="1" />
        <div class="widget">
          <div class="wizard swMain">
            <ul>
              <li><a href="#step-1" class="bordLeft wFirst">
                <h5 class="stepDesc iComputer">Sicherheitsschl&uuml;ssel</h5>
              </a></li>
              <li><a href="#step-2" class="bordRight">
                <h5 class="stepDesc iSpeech">Inhaltszuweisung</h5>
              </a></li>
            </ul>
            <div id="step-1">
            
              <div class="rowElem nobg" >
                <label  style="width:150px"><b>API Sicherheitsschl&uuml;ssel:</b></label>
                <div class="formRight"  style="width:500px">
                  <input type="text" name="haendlerbund_key" value="' . $this->getConfigurationValue("haendlerbund_key") . '" id="haendlerbund_key"/>
                </div>
                <div class="fix"></div>
              </div>
              <div class="fix"></div>
            </div>
            <div id="step-2" style="height:350px">
              <p> Bitte weisen Sie jedem Rechtstext einen passenden Inhalt aus dem Content-Manager zu. <br />
<b>Achten Sie darauf, dass jeder Rechtstext einen unterschiedlichen Content zugewiesen ist.</b></p>';

            $return .= '<strong id="text"><center><br /><br />

<img src="includes/haendlerbund/images/loading.gif" /><br />
<br />
Einen Moment bitte, es wird geladen!</center></strong>';

            $return .= '<br style="clear: both" /><br/>';
            $return .='   </div>
          </div>
          <div class="fix"></div>
        </div>
    
    </form>
  
  
  </div>';
        } else {

            $return .= '<div class="content" id="container">
    <div class="title_hb">
	
	
      <h5 class="title_hb">Rechtstexte importieren</h5></div>';



            $return .= '
	<br />
	<form action="" name="AGBimport" method="post">
	<input type="hidden" name="agb_import" value="1" />
        <div style="width:731px; height:300px; background-image:url(includes/haendlerbund/images/import_picture.jpg); background-position:top;"><div style="padding:10px; padding-top:50px;">
		
		
		<div style="line-height:200%; width:260px; float:left; padding-top:110px; font-size:10px">' . $this->rt_gen() . '</div>
		
		
        <div style="float:left; width:216px;">
        <div style="line-height:125%;">';

            if ($_SESSION["import_message"] != "") {

                $return .= '<img src="includes/haendlerbund/images/import_ok_btn.png" width="217" height="52">';
                $_SESSION["import_message"] = "";
            } else {

                $return .= '<img src="includes/haendlerbund/images/pfleil_blue.png" width="217" height="52"><span style="color:#1E4565; font-weight:bold;"><br>
          WICHTIG!</span>  <br>
 Mit Ausf&uuml;hren des Imports werden alle bisher vorhandenen Rechtstexte ersetzt!<br>
 <br>
 <br>
<input type="submit" name="import" value="" style="background-image:url(includes/haendlerbund/images/import_btn.png); width:196px; height:26px; border:0;" />';
            }

            $return .= '</div>
</div>
        
        
        
		</div></div><br>
  <a href="?start_konfig=1"><img src="includes/haendlerbund/images/konfig_btn.png" width="175" height="23" border="0"></a>
</form>';



            $return .= " </div>  ";
        }



        return $return;
    }

    function rt_gen() {





        $agb_service = array(
            "Impressum" => "haendlerbund_impressum",
            "AGB" => "haendlerbund_agb",
            "Widerrufsrecht" => "haendlerbund_widerruf",
            "R&uuml;ckgaberecht" => "haendlerbund_rueckgabe",
            "Zahlung und Versand" => "haendlerbund_versandinfo",
            "Datenschutzerkl&auml;rung" => "haendlerbund_datenschutz",
            "Hinweise zur Batterieentsorgung" => "haendlerbund_batteriegesetz"
        );



        $rt_field = "";

        $sql_check = mysql_query("SELECT configuration_key  FROM configuration WHERE configuration_key LIKE '%_hbon' AND configuration_value = 1 ORDER BY  configuration_id");
        while ($agb = mysql_fetch_array($sql_check)) {
            $key = str_replace("_hbon", "", $agb["configuration_key"]);



            $rt_field .= '<br /><img src="includes/haendlerbund/images/arrow.png" /> &nbsp;&nbsp;' . array_search($key, $agb_service);
        }

        return $rt_field;
    }

    #getSelect Methode: Generiert ein Select-Formularfeld

    function getSelect($label, $name, $id, $options) {
        $return .= $this->getLabel($label, $id, $true);
        $return .= "<select name='" . $name . "' id='" . $id . "'>";
        if ($this->getConfigurationValue($name) AND !$value) {
            $value = $this->getConfigurationValue($name);
        } elseif ($_POST[$name]) {
            $data = $this->getFormData(array($name));
            $value = $data[$name];
        }
        foreach ($options as $key => $option) {
            $selected = "";
            if ($option == $value)
                $selected = " selected='selected'";
            $return .= "<option value='" . $option . "'" . $selected . ">" . $option . "</option>";
        }
        $return .= "</select>";
        return $return;
    }

    #getLabel Methode: Generiert ein Label fuer ein Formularfeld

    function getLabel($label, $id, $required = false, $style = 'float:left;width:250px;') {
        if ($required)
            $star = "*";
        return "<label for='" . $id . "' id='" . $id . "_label' style='" . $style . "'>" . $label . $star . "</label>";
    }

    function getInputForm($type, $value, $label, $name, $id, $required = true, $function = '') {
        if ($this->getConfigurationValue($name) AND !$value) {
            $value = $this->getConfigurationValue($name);
        } elseif ($_POST[$name]) {
            $data = $this->getFormData(array($name));
            $value = $data[$name];
        }
        return $this->getLabel($label, $id, $required) . "<input type='" . $type . "' name='" . $name . "' id='" . $id . "' value='" . $value . "' onChange='" . $function . "' />";
    }

    #getContentIDSelect Methode: Generiert ein Select-Formularfeld mit allen Inhalten des SHops

    function getContentIDSelect($label, $name, $id, $required = true, $lang = 1) {
        $return = $this->getLabel($label, $id, $required) . "<select name='" . $name . "' id='" . $id . "'>";
        if ($this->getConfigurationValue($name) AND !$value) {
            $value = $this->getConfigurationValue($name);
        } elseif ($_POST[$name]) {
            $data = $this->getFormData(array($name));
            $value = $data[$name];
        }

        $sql = mysql_query("SELECT content_id,content_title FROM content_manager WHERE languages_id=" . $_SESSION["languages_id"] . " ORDER BY content_title");
        while ($row = mysql_fetch_object($sql)) {
            $selected = "";

            if ($row->content_id == $value)
                $selected = " selected='selected'";
            $return .= "<option value='" . $row->content_id . "'" . $selected . ">" . $row->content_title . "</option>";
        }
        $return .= "</select>";
        return $return;
    }

}
